package cn.bearspark.common.parse.host;

import cn.bearspark.common.parse.Parser;

/**
 * 主机 ip 地址的解析器
 *
 * @author f
 */
public class HostParser extends Parser<HostTextContext> {

    /**
     * 主机 ip 地址 + http:// 的前缀
     */
    private final String srcPrefix = "http://" + HostTextContext.HOST;

    /**
     * http://<h> 的前缀
     */
    private final String tarPrefix = "http://<h>";

    @Override
    public void parse() {
        HostTextContext context = pipeline().getContext();
        String src = context.getBody();
        int index = 0;
        while (true) {
            int openIndex = src.indexOf(srcPrefix, index);
            if (openIndex == -1) {
                context.setBody(src);
                return;
            }
            int closeIndex = src.indexOf("/", openIndex + srcPrefix.length());
            src = src.substring(0, openIndex) +
                  tarPrefix +
                  src.substring(closeIndex);
            index = closeIndex + "/".length();
        }
    }

    @Override
    public void unparse() {
        HostTextContext context = pipeline().getContext();
        String tar = context.getBody();
        int index = 0;
        while (true) {
            int openIndex = tar.indexOf(tarPrefix, index);
            if (openIndex == -1) {
                context.setBody(tar);
                return;
            }
            tar = tar.substring(0, openIndex) +
                  srcPrefix +
                  tar.substring(openIndex + tarPrefix.length());
            index = tar.indexOf("/", openIndex + srcPrefix.length()) + "/".length();
        }
    }
}
